#include "featuresproxymodel.h"

#include <dtwentymodel.h>
#include <characterfeature.h>


FeaturesProxyModel::FeaturesProxyModel(QObject *parent) :
    QSortFilterProxyModel(parent)
{
}

QVariant FeaturesProxyModel::data(const QModelIndex &index, int role) const
{
    if (index.column() != 2)
    {
        return QSortFilterProxyModel::data(index, role);
    }

    if (role != Qt::DisplayRole && role != Qt::EditRole && role != DTwentyModel::Role_VALUE_OPTIONS)
    {
        return QSortFilterProxyModel::data(index, role);
    }

    QModelIndex sourceIndex = mapToSource(index);
    if (!sourceIndex.isValid())
    {
        return QSortFilterProxyModel::data(index, role);
    }

    CharacterFeature* feature = reinterpret_cast<CharacterFeature*>(sourceIndex.internalPointer());
    if (!feature)
    {
        return QSortFilterProxyModel::data(index, role);
    }

    int featureId = feature->id();
    if (featureId >= CharacterFeatures::Feature_CUSTOM)
    {
        return QSortFilterProxyModel::data(index, role);
    }

    const QMetaObject* mo = feature->metaObject();
    int enumOffset = mo->enumeratorOffset();
    int enumCount = mo->enumeratorCount();
    int enumPos = featureId + enumOffset;

    if (enumPos >= enumCount)
    {
        enumPos = enumCount-1;
    }

    QMetaEnum me = mo->enumerator(enumPos);

    switch (role) {
    case Qt::DisplayRole:
        return me.valueToKey(feature->value());

    case Qt::EditRole:
        return feature->value();

    case DTwentyModel::Role_VALUE_OPTIONS:
    {
        QVariantMap ret;
        for (int i = 0; i < me.keyCount(); i++)
        {
            QString name = me.key(i);
            QVariant value = me.value(i);

            ret.insert(name, value);
        }
        return ret;
    }

    default:
        break;
    }

    return QSortFilterProxyModel::data(index, role);
}
